#![allow(non_snake_case)]
use crate::{
    components::{ server_error::ServerError, ButtonList, CommonPage, DataRange },
    shhr::{ credit_report_flow, get_shhr_dept, transaction_flow },
};
use icondata as i;
use leptos::prelude::*;
use serde_json::Value;
use shq_common::prelude::{ AndOr, FliterItem, Operator, User, WhereCause };
use shq_web_controls::{
    use_message,
    MessageOptions,
    MessageVariant,
};
use thaw_utils::ArcOneCallback;

#[derive(Clone)]
pub struct SelectIds {
    ids: Vec<u64>,
}
impl SelectIds {
    pub fn new() -> Self {
        SelectIds { ids: Vec::new() }
    }
    pub fn from(ids: Vec<u64>) -> Self {
        SelectIds { ids }
    }
    pub fn get_ids(&self) -> Vec<u64> {
        self.ids.clone()
    }
}
#[component]
pub fn Ygzygl(menu_id: u32, ny: RwSignal<u32>, wfid: u32) -> impl IntoView {
    let release: RwSignal<bool> = RwSignal::new(false);
    let get_dept_id = LocalResource::new(move || get_shhr_dept(ny.get(), wfid));
    let mess = use_message();
    let curr_user = use_context::<RwSignal<Option<User>>>().unwrap();
    let userid = curr_user.with(|u| u.as_ref().map(|u| u.id).unwrap_or_default());
    let save_user_action = Action::new(move |emids: &Vec<u32>| {
        let ny_val = ny.get();
        let emids = emids.clone();
        async move {
            if wfid == 1 {
                match credit_report_flow(ny_val, userid, emids).await {
                    Ok(_) => {
                        mess.create("发布成功", MessageVariant::Success, MessageOptions::default());
                        release.set(false);
                        ny.set(ny.get());
                    }
                    Err(e) => {
                        mess.create(
                            format!("发布失败：{}", e),
                            MessageVariant::Error,
                            MessageOptions::default()
                        );
                    }
                }
            } else if wfid == 2 {
                match transaction_flow(ny_val, userid, emids).await {
                    Ok(_) => {
                        mess.create("发布成功", MessageVariant::Success, MessageOptions::default());
                        release.set(false);
                        ny.set(ny.get());
                    }
                    Err(e) => {
                        mess.create(
                            format!("发布失败：{}", e),
                            MessageVariant::Error,
                            MessageOptions::default()
                        );
                    }
                }
            }
            release.set(false);
        }
    });
    let release_specialist_mana = ArcOneCallback::new(move |rows:Vec<Value>| {
        if !rows.is_empty()  {
            let mut emids = Vec::new();
            for row in rows {
                if let Some(obj) = row.as_object() {
                    if let Some(jemid) = obj.get("id") {
                        if let Some(emid) = jemid.as_u64() {
                            emids.push(emid as u32);
                        }
                    }
                }
            }
            if !emids.is_empty() {
                save_user_action.dispatch(emids);
            } else {
                mess.create(
                    "选择的记录中没有有效的员工ID",
                    MessageVariant::Warning,
                    MessageOptions::default(),
                );
            }
        }else{
            mess.create(
                "没有选择任何数据",
                MessageVariant::Warning,
                MessageOptions::default(),
            );
        }
    });
    let custom_buttons1 = {
        let mut bl=ButtonList::new();
        bl.add_custom(
            "发布".to_string(),
            Some(i::SiSemanticrelease),
            None,
            Some("您确定要发布吗？".to_string()),
                DataRange::Selected,
                vec!["id"],
            release_specialist_mana,
        );
        bl
    };
    // 发布页面
    // let release_page = move || {
    //     release.get().then(||
    //         view! {
    //             <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    //                 <div class="bg-white rounded-lg p-6 max-w-md w-full">
    //                     <h3 class="text-lg font-medium text-gray-900 mb-4">"确认发布"</h3>
    //                     <p class="text-gray-700 mb-6">"你确定要发布当前流程吗?"</p>
    //                     <div class="flex justify-end space-x-4">
    //                         <button
    //                             class="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300 transition-colors"
    //                             on:click=move |_| release.set(false)
    //                         >
    //                             "取消"
    //                         </button>
    //                         <button
    //                             class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
    //                             on:click=move |_| {
    //                                 release.set(false);
    //                                 save_user_action.dispatch(());
    //                             }
    //                         >
    //                             "确认发布"
    //                         </button>
    //                     </div>
    //                 </div>
    //             </div>
    //         })
    // };
    let yg_commonpage = move || {
        let custom_buttons1 = custom_buttons1.clone();
        match get_dept_id.get().as_deref() {
            None => either_of::EitherOf4::A(view! { <p>"Loading..."</p> }),
            Some(res) => {
                match res.clone() {
                    Ok(ids) => {
                        if ids.is_empty() {
                            return either_of::EitherOf4::C(view! {
                                <p>"请在左侧添加部门"</p>
                            });
                        }
                        let init_filters = Signal::derive(move || {
                            vec![WhereCause {
                                field_name: "organ_id".to_string(),
                                filter_items: vec![FliterItem {
                                    // 确保这里使用的是正确的 FilterItem 结构体名称
                                    operator: Operator::In,
                                    value: Some(
                                        ids
                                            .iter()
                                            .map(|id| id.to_string())
                                            .collect::<Vec<String>>()
                                            .join(",")
                                    ),
                                }],
                                and_or: AndOr::And,
                            }]
                        });
                        either_of::EitherOf4::B(
                            view! {
                                <CommonPage menu_id conf_name="uset_approvers" custom_buttons=custom_buttons1 init_filters=init_filters/>
                            }
                        )
                    }
                    Err(err) =>
                        either_of::EitherOf4::D(
                            view! { <ServerError err_msg=err.to_string().into()/> }
                        ),
                }
            }
        }
    };
    view! {
        <div class="flex flex-1 gap-2 min-h-1 w-full h-full overflow-hidden">
        <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                {yg_commonpage}
        </Suspense>
        // <ToasterProvider position=ToastPosition::TopStart>
        //     {release_page}
        // </ToasterProvider>
        </div>
    }
}
